import type { Plugin } from 'vuepress/core';

import type MarkdownIt from "markdown-it";
import MarkdownContainer from 'markdown-it-container'
import fs from 'fs-extra'
import {path} from "vuepress/utils"


const getComponentName = (filename) => path.trimExt(filename.replace(/\/|\\/g, '-'))


export const ImportDemoBlock = (options: {componentDir: string}):Plugin => {
  const component = "demo-block"
  const { componentDir } = options;
  const componentName = component.replace(/^\S/, s => s.toLowerCase()).replace(/([A-Z])/g, "-$1").toLowerCase();
  
  return (md:MarkdownIt) =>  {
    md.use(MarkdownContainer, 'demo', {
      validate: (params) => params.trim().match(/^demo\s*(.*)$/),
      render (tokens, idx) {
        const m = tokens[idx].info.trim().match(/^demo\s*(.*)$/);

        if (tokens[idx].nesting === 1) {
          const sourceFileToken = tokens[idx + 2]
          const sourceFile = sourceFileToken.children?.[0].content ?? ''
          const source = sourceFileToken.type === 'inline' ?  fs.readFileSync(path.resolve(`${componentDir}/${sourceFile}.vue`), 'utf-8') : ''
          const ComponentName = getComponentName(sourceFile)
          return `<${componentName} componentName="${ComponentName}" componentSource="${encodeURIComponent(componentDir)}"
          source="${encodeURIComponent(md.options.highlight?.(source, 'vue', ''))}"
          >
        `;
        }
        return `</${componentName}>`;
      }
    });
  };
}
